package com.qkl.xiatang.app.utils;


import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AppTokenUtils {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String SECRET_KEY = "930ea87834d64983846dede48fa1025a";
    private static final int TOKEN_PREFIX_LEN = 10;

    public static String encryptUserId(String userId)  {
        String prefix = AppUtils.randomChars(TOKEN_PREFIX_LEN);
        return encrypt(prefix + userId);
    }

    public static String encrypt(String plainText)  {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptUserId(String token) {
        String decryptStr = decrypt(token);
        if(StringUtils.isNotEmpty(decryptStr) && decryptStr.length() >= TOKEN_PREFIX_LEN){
            return decryptStr.substring(TOKEN_PREFIX_LEN);
        }
        return "";
    }

    public static String decrypt(String cipherText) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
            return new String(decryptedBytes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) throws Exception {
        String userId = "1772451560433573890";
        String token = encryptUserId(userId);
        //token = "GsegLnJFes+ZyFftD+1xk8XQYkKfu/hon+ExOULlBYo=";
        String decryptUserId = decryptUserId(token);
        System.out.println(userId);
        System.out.println(token);
        System.out.println(decryptUserId);
        //System.out.println(UUID.randomUUID().toString().replaceAll("-",""));

    }
}
